package cn.caplike.demo.rabbitmq.springboot.idempotence_reliability.application;

import cn.caplike.demo.rabbitmq.springboot.idempotence_reliability.common.domain.model.MailRequest;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Locale;
import java.util.UUID;

/**
 * Description: 邮件发送服务
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-09-01 16:39
 */
@Service
public class MailSendingService {

    private static final String MAIL_SENDER = "caplike@163.com";

    private JavaMailSender mailSender;

    /**
     * {@code Thymeleaf} 模板引擎
     */
    private TemplateEngine templateEngine;

    /**
     * Description: 发送邮件
     *
     * @param mailRequest 邮件内容实体
     * @return void
     * @throws RuntimeException 如果发送邮件异常
     * @author LiKe
     * @date 2020-09-01 17:01:10
     */
    public void send(MailRequest mailRequest) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(MAIL_SENDER);
            mimeMessageHelper.setTo(mailRequest.getReceiver());
            mimeMessageHelper.setSubject("Client Secret Notification!");
            mimeMessageHelper.setText(
                    templateEngine.process(
                            "mail/template-client-secret-request",
                            new Context(
                                    Locale.CHINESE,
                                    MapUtils.putAll(new HashMap<>(), new String[]{
                                            "clientId", StringUtils.upperCase(mailRequest.getClientId()),
                                            "clientSecret", UUID.randomUUID().toString()
                                    })
                            )
                    ), true);
            mailSender.send(mimeMessage);
        } catch (MessagingException ex) {
            throw new RuntimeException(ex);
        }
    }

    // ~ Autowired
    // -----------------------------------------------------------------------------------------------------------------

    @Autowired
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Autowired
    public void setTemplateEngine(TemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }
}
